// 退款审批处理模块
class RefundApproval {
    constructor() {
        this.refundTypes = {
            quality: '质量问题',
            delivery: '配送问题',
            customer: '客户原因',
            merchant: '商家原因'
        };
        
        this.approvalStatus = {
            pending: '待审核',
            firstApproved: '一级已审核',
            finalApproved: '终审通过',
            rejected: '已拒绝'
        };
        
        this.thresholds = {
            autoApproval: 50,    // 自动审批金额阈值
            firstLevel: 200,     // 一级审批金额阈值
            secondLevel: 1000    // 二级审批金额阈值
        };
        
        this.init();
    }
    
    init() {
        // 确保DOM加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.initializeContent();
            });
        } else {
            this.initializeContent();
        }
    }

    initializeContent() {
        this.showRefundApprovalContent();
        this.renderRefundList();
        this.bindEvents();
        this.startAutoRefresh();
    }

    showRefundApprovalContent() {
        // 确保必要的DOM结构存在
        let contentWrapper = document.querySelector('.content-wrapper');
        if (!contentWrapper) {
            contentWrapper = document.createElement('div');
            contentWrapper.className = 'content-wrapper';
            document.body.appendChild(contentWrapper);
        }

        // 清空现有内容
        contentWrapper.innerHTML = '';

        // 创建退款审批容器
        const refundApproval = document.createElement('div');
        refundApproval.className = 'refund-approval';
        
        // 创建退款列表容器
        const refundList = document.createElement('div');
        refundList.className = 'refund-list';
        refundApproval.appendChild(refundList);
        
        // 添加到页面
        contentWrapper.appendChild(refundApproval);
    }
    
    // 获取退款申请列表
    async fetchRefundApplications() {
        // 模拟异步获取数据
        return new Promise(resolve => {
            setTimeout(() => {
                resolve([
                    {
                        id: 'RF20230001',
                        orderId: 'DD20230001',
                        type: 'quality',
                        amount: 45.00,
                        status: 'pending',
                        createTime: '2023-12-20 14:30:00',
                        reason: '食品质量问题',
                        evidence: ['photo1.jpg', 'photo2.jpg'],
                        approvalChain: []
                    },
                    {
                        id: 'RF20230002',
                        orderId: 'DD20230002',
                        type: 'delivery',
                        amount: 180.00,
                        status: 'firstApproved',
                        createTime: '2023-12-20 14:25:00',
                        reason: '超时配送',
                        evidence: ['delivery_record.jpg'],
                        approvalChain: [
                            {
                                level: 1,
                                approver: '张经理',
                                time: '2023-12-20 14:28:00',
                                result: 'approved',
                                comment: '配送延迟确实存在，同意退款'
                            }
                        ]
                    }
                ]);
            }, 500);
        });
    }
    
    // 渲染退款申请列表
    async renderRefundList() {
        const applications = await this.fetchRefundApplications();
        const container = document.querySelector('.content-wrapper .refund-list');
        
        if (!container) {
            const contentWrapper = document.querySelector('.content-wrapper');
            if (contentWrapper) {
                contentWrapper.innerHTML = '<div class="refund-list"></div>';
            }
            return;
        }
        
        if (!applications.length) {
            container.innerHTML = this.renderEmptyState();
            return;
        }
        
        container.innerHTML = applications.map(app => this.renderRefundItem(app)).join('');
    }
    
    // 渲染单个退款申请项
    renderRefundItem(application) {
        return `
            <div class="refund-item" data-id="${application.id}">
                <div class="refund-info">
                    <div class="refund-header">
                        <span class="refund-id">${application.id}</span>
                        <span class="refund-type type-${application.type}">
                            ${this.refundTypes[application.type]}
                        </span>
                        <span class="status-tag status-${application.status}">
                            ${this.approvalStatus[application.status]}
                        </span>
                    </div>
                    <div class="refund-details">
                        <div class="amount">退款金额: ¥${application.amount.toFixed(2)}</div>
                        <div class="reason">原因: ${application.reason}</div>
                    </div>
                    <div class="approval-chain">
                        ${this.renderApprovalChain(application.approvalChain)}
                    </div>
                </div>
                <div class="action-buttons">
                    ${this.renderActionButtons(application)}
                </div>
            </div>
        `;
    }
    
    // 渲染审批链
    renderApprovalChain(chain) {
        if (!chain.length) return '';
        
        return `
            <div class="approval-history">
                ${chain.map(record => `
                    <div class="approval-record">
                        <span class="approval-time">${record.time}</span>
                        <span class="approver">${record.approver}</span>
                        <span class="approval-result result-${record.result}">
                            ${record.result === 'approved' ? '通过' : '拒绝'}
                        </span>
                        ${record.comment ? `<div class="comment">${record.comment}</div>` : ''}
                    </div>
                `).join('')}
            </div>
        `;
    }
    
    // 渲染操作按钮
    renderActionButtons(application) {
        if (application.status === 'finalApproved' || application.status === 'rejected') {
            return `
                <button class="action-button button-default" onclick="refundApproval.viewDetail('${application.id}')">
                    查看详情
                </button>
            `;
        }
        
        return `
            <button class="action-button button-primary" onclick="refundApproval.handleApproval('${application.id}')">
                ${this.getActionButtonText(application)}
            </button>
            <button class="action-button button-default" onclick="refundApproval.viewDetail('${application.id}')">
                查看详情
            </button>
        `;
    }
    
    // 获取操作按钮文本
    getActionButtonText(application) {
        switch (application.status) {
            case 'pending':
                return '审核';
            case 'firstApproved':
                return '终审';
            default:
                return '处理';
        }
    }
    
    // 渲染空状态
    renderEmptyState() {
        return `
            <div class="empty-state">
                <div class="empty-state-icon">📋</div>
                <div>暂无退款申请</div>
            </div>
        `;
    }
    
    // 处理退款审批
    async handleApproval(refundId) {
        const application = await this.getRefundDetail(refundId);
        if (!application) return;
        
        // 根据金额判断审批流程
        if (application.amount <= this.thresholds.autoApproval) {
            await this.autoApprove(application);
        } else if (application.amount <= this.thresholds.firstLevel) {
            await this.firstLevelApproval(application);
        } else {
            await this.secondLevelApproval(application);
        }
        
        // 刷新列表
        this.renderRefundList();
    }
    
    // 自动审批
    async autoApprove(application) {
        // 实现自动审批逻辑
        console.log('自动审批:', application);
        // 模拟API调用
        return new Promise(resolve => {
            setTimeout(() => {
                application.status = 'finalApproved';
                application.approvalChain.push({
                    level: 0,
                    approver: 'System',
                    time: new Date().toISOString(),
                    result: 'approved',
                    comment: '符合自动审批条件'
                });
                resolve(application);
            }, 300);
        });
    }
    
    // 一级审批
    async firstLevelApproval(application) {
        // 实现一级审批逻辑
        console.log('一级审批:', application);
        // TODO: 实现审批界面和逻辑
    }
    
    // 二级审批
    async secondLevelApproval(application) {
        // 实现二级审批逻辑
        console.log('二级审批:', application);
        // TODO: 实现审批界面和逻辑
    }
    
    // 查看退款详情
    async viewDetail(refundId) {
        const application = await this.getRefundDetail(refundId);
        if (!application) return;
        
        // 实现查看详情的弹窗逻辑
        console.log('查看退款详情:', application);
    }
    
    // 获取退款详情
    async getRefundDetail(refundId) {
        // 模拟获取退款详情
        return new Promise(resolve => {
            setTimeout(() => {
                const applications = [
                    {
                        id: 'RF20230001',
                        orderId: 'DD20230001',
                        type: 'quality',
                        amount: 45.00,
                        status: 'pending',
                        createTime: '2023-12-20 14:30:00',
                        reason: '食品质量问题',
                        evidence: ['photo1.jpg', 'photo2.jpg'],
                        approvalChain: []
                    }
                ];
                resolve(applications.find(app => app.id === refundId));
            }, 300);
        });
    }
    
    // 绑定事件
    bindEvents() {
        // 绑定刷新按钮事件
        const refreshButton = document.createElement('button');
        refreshButton.className = 'action-button button-default refresh-button';
        refreshButton.innerHTML = '刷新列表';
        refreshButton.onclick = () => this.renderRefundList();
        
        const contentWrapper = document.querySelector('.content-wrapper');
        if (contentWrapper) {
            const header = document.createElement('div');
            header.className = 'refund-header';
            header.appendChild(refreshButton);
            contentWrapper.insertBefore(header, contentWrapper.firstChild);
        }

        // 为所有退款项添加悬停效果
        document.addEventListener('mouseover', (e) => {
            const refundItem = e.target.closest('.refund-item');
            if (refundItem) {
                refundItem.style.transform = 'translateY(-2px)';
            }
        });

        document.addEventListener('mouseout', (e) => {
            const refundItem = e.target.closest('.refund-item');
            if (refundItem) {
                refundItem.style.transform = 'none';
            }
        });
    }
    
    // 启动自动刷新
    startAutoRefresh() {
        setInterval(() => this.renderRefundList(), 30000); // 每30秒刷新一次
    }
}

// 导出退款审批处理类
export default RefundApproval;